﻿using DG.Tweening;

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class UIBattleChallenge : UIObject // required interface when using the OnEndDrag method.
{
    public UIBattleScrollClamp diceScroll;
    public InputField inputFieldDiceNum;
    public Toggle toggleIsVegetable;
    protected override void onVisible()
    {
        Facade.Instance.RegistNetEvent(nameof(actionbattle_rsp), OnHandleActionbattleRsp);
    }

    protected override void OnInvisible()
    {
        Facade.Instance.UnRegistNetEvent(nameof(actionbattle_rsp), OnHandleActionbattleRsp);
    }

    public void OnButtonChallengeClick(Button button)
    {
        if(BattleCtr.Instance.dataBattleMgr.ChallengeUid != DataPlayer.Instance.userId)
        {
            UIDialog.Instance.Show(XLocalization.Get("警告"), XLocalization.Get("还没轮到你喊骰子，你执意喊骰子，破坏规则吗？"), () =>
            {
                DoChallengeAction(button);
            }, null);
            return;
        }

        DoChallengeAction(button);
    }

    private void DoChallengeAction(Button button)
    {
        var req1 = new actionbattle();
        req1.type = ActionType.Challenge;
        req1.touid = "";//temp
        req1.content = inputFieldDiceNum.text.Trim() + "," + (int)diceScroll.GetDiceType() + (toggleIsVegetable.isOn ? ",true" : ",false");
        WebSocketClient.Instance.SendSerialize(button, req1);
    }

    private void OnHandleActionbattleRsp(System.Object data)
    {
        var rsp = data as actionbattle_rsp;
        if (rsp.ret != NetErrorCode.None)
        {
            UITips.Instance.Show("出错了:" + rsp.ret + " " + rsp.reason);
        }
    }

    private DataBattleMgr _dataBattleMgr;
    public void Bind(DataBattleMgr data)
    {
        _dataBattleMgr = data;
        inputFieldDiceNum.text = data.GetDataPlayerCount().ToString();
    }

    public void Unbind()
    {
        _dataBattleMgr = null;
    }

    public void OnButtonDiceNumAdd()
    {
        int num;
        if(!int.TryParse(inputFieldDiceNum.text.Trim(), out num))
        {
            num = 1;
        }
        num++;
        inputFieldDiceNum.text = num.ToString();
    }

    public void OnButtonDiceNumMinus()
    {
        int num;
        if (!int.TryParse(inputFieldDiceNum.text.Trim(), out num))
        {
            num = 1;
        }
        num--;
        if (num < 1)
            num = 1;
        inputFieldDiceNum.text = num.ToString();
    }
}
